package chen.web.user;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import chen.web.BusinessException;
import chen.web.config.ConfigRepository;
import chen.web.config.SiteConfig;
import chen.web.email.EmailAddress;
import chen.web.email.EmailSender;
import chen.web.email.SimpleEmail;
import chen.web.event.EventListener;
import chen.web.user.event.RegisterEvent;
import chen.web.util.FreeMarker;

public class SendRegisterEmail implements EventListener<RegisterEvent> {

	private static Log log = LogFactory.getLog(SendRegisterEmail.class);
	private EmailSender sender;
	private boolean validateEmail = false;
	
	public SendRegisterEmail(EmailSender sender){
		this(sender, false);
	}
	
	public SendRegisterEmail(EmailSender sender, boolean validateEmail){
		this.sender = sender;
		this.validateEmail = validateEmail;
	}
	
	@Override
	public void listen(RegisterEvent event) {
		// TODO Auto-generated method stub
		Account account = event.getRegisterAccount();
		if(validateEmail)
			sendValidateMail(account);
		else
			sendMail(account);
	}
	
	private void sendMail(Account account){
		SiteConfig siteConfig = ConfigRepository.instance().get(SiteConfig.class);
		//新建邮件
		SimpleEmail email = new SimpleEmail();
		//邮件主题
		email.setSubject(account.getNickname() + "，您在" + siteConfig.getSiteName() + "的账号注册成功");
		//准备渲染模板的数据
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("nickname", account.getNickname());
		data.put("siteName", siteConfig.getSiteName());
		data.put("baseURL", siteConfig.getBaseURL());
		//渲染模板
		String html = FreeMarker.process("register_success.flt", data);
		//邮件内容
		email.setHtml(html);
		//收件人
		email.setTo(new EmailAddress(account.getEmail()));
		//发送邮件
		sender.send(email);
	}
	
	private void sendValidateMail(Account account){
		//新建邮件
		SimpleEmail email = new SimpleEmail();
		//邮件主题
		email.setSubject("会员帐号注册成功，就等您激活了");
		//准备渲染模板的数据
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("nickname", account.getNickname());
		//渲染模板
		String html = FreeMarker.process("email_validation.flt", data);
		//邮件内容
		email.setHtml(html);
		//收件人
		email.setTo(new EmailAddress(account.getEmail()));
		//发送邮件
		if(!sender.send(email)){
			String info = new StringBuffer().append("用于验证注册用户邮箱的邮件发送出现错误[")
			.append(account.getNickname())
			.append(",")
			.append(account.getEmail())
			.append("]")
			.toString();
			log.error(info);
			throw new BusinessException(BusinessException.Email_Sending_Failed);
		}
		
	}

}
